package com.zy.qudadid.utils;

import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts.Data;
import android.provider.ContactsContract.RawContacts;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author  lc 
 * @date 创建时间：2016-1-13 上午10:13:27 
 * @version 1.0 
 * @Description 打印工具类
 */
public class ToolsUtil {
	
	private static final String TAG = "ToolsUtil";
	
	// 打印方法
	public static void print(String tag, String msg) {
		if(true){
			Log.i(tag, msg);
		}
	}

	
//	/**
//	 * Exception 信息提示
//	 */
//	public static void Notic(Context context, String notic,
//			OnClickListener listener) {
//		UIDialog.ForNotic(context, notic, listener);
//	}
	
	/**
	 * 获取当前应用的版本号
	 */

	public static int getAppVersion(Context context) {
		int version = 0;
		try {
			PackageInfo packinfo = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			version = packinfo.versionCode;
		} catch (Exception e) {
			e.printStackTrace();
			return version;
		}

		return version;
	}
	
	/**
	 * 格式化时间
	 * @param time 
	 * @return 
	 */
	public static String formatDateTime(String time) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		if(time==null ||"".equals(time)){
			return "";
		}
		Date date = null;
		try {
			date = format.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		Calendar current = Calendar.getInstance();
		
		Calendar today = Calendar.getInstance();	//今天
		
		today.set(Calendar.YEAR, current.get(Calendar.YEAR));
		today.set(Calendar.MONTH, current.get(Calendar.MONTH));
		today.set(Calendar.DAY_OF_MONTH,current.get(Calendar.DAY_OF_MONTH));
		//  Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数
		today.set( Calendar.HOUR_OF_DAY, 0);
		today.set( Calendar.MINUTE, 0);
		today.set(Calendar.SECOND, 0);
		
		Calendar yesterday = Calendar.getInstance();	//昨天
		
		yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
		yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
		yesterday.set(Calendar.DAY_OF_MONTH,current.get(Calendar.DAY_OF_MONTH)-1);
		yesterday.set( Calendar.HOUR_OF_DAY, 0);
		yesterday.set( Calendar.MINUTE, 0);
		yesterday.set(Calendar.SECOND, 0);
		
		current.setTime(date);
		
		if(current.after(today)){
			return "今天 "+time.split(" ")[1];
		}else if(current.before(today) && current.after(yesterday)){
			
			return "昨天 "+time.split(" ")[1];
		}else{
			int index = time.indexOf("-")+1;
			return time.substring(index, time.length());
		}
	}
	
	int i = 0;
	
	/**
	  * 往数据库中新增联系人
	  * 
	  * @param name
	  * @param number
	  */
	 public static void AddContact(Context mContext,String name, String number) {
		 
		  ContentValues values = new ContentValues();
		  // 首先向RawContacts.CONTENT_URI执行一个空值插入，目的是获取系统返回的rawContactId
		  Uri rawContactUri = mContext.getContentResolver().insert(
		    RawContacts.CONTENT_URI, values);
		  long rawContactId = ContentUris.parseId(rawContactUri);
		  // 往data表插入姓名数据
		  values.clear();
		  values.put(Data.RAW_CONTACT_ID, rawContactId);
		  values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);// 内容类型
		  values.put(StructuredName.GIVEN_NAME, name);
		  mContext.getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
		    values);
	
		  // 往data表插入电话数据
		  values.clear();
		  values.put(Data.RAW_CONTACT_ID, rawContactId);
		  values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
		  values.put(Phone.NUMBER, number);
		  values.put(Phone.TYPE, Phone.TYPE_MOBILE);
		  mContext.getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
		    values);
		  
		  ToolsUtil.print("----", name);
	 }
	 
	 /**
	 * 判断是否是手机号的正则
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("[1][3578]\\d{9}");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }
	 
	public static String mURLEncoder(String str){
		String strNew = null;
		try {
			strNew = URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return strNew;
	}
	
	 /**
     * 设置部分文本字体颜色值
     *
     * @param textView 文本框
     * @param text     文本内容
     * @param start    设置的文本起点
     * @param end      设置的文本终点
     * @param colorId  颜色值ID
     */
    public static void setPartTextColor(TextView textView, String text,
                                        int start, int end, int colorId) {
        SpannableString ss = new SpannableString(text);
        ss.setSpan(new ForegroundColorSpan(colorId), start, end,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(ss);
    }


	public static String getRandomString(int length) { //length表示生成字符串的长度
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}


	public static boolean isValidDate(String str) {
		boolean convertSuccess=true;
		// 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
			format.setLenient(false);
			format.parse(str);
		} catch (ParseException e) {
			// e.printStackTrace();
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			convertSuccess=false;
		}
		return convertSuccess;
	}

	//退出操作
	public static void exitkey(int keyCode, Context context) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {// 返回按钮
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setTitle("提示").setMessage("您确定退出当前应用").setNegativeButton("取消", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
//					try {
//						// 判断是否存在临时创建的文件
//						File temp_file = new File(Environment.getExternalStorageDirectory() + File.separator + "heyi_dir");
//						if (temp_file.exists()) {
//							File[] file_detail = temp_file.listFiles();
//							for (File file_del : file_detail) {
//								file_del.delete();
//							}
//							temp_file.delete();
//						}
//					} catch (Exception e) {
//					}
					ActivityUtil.finishActivitys();
					System.exit(0);
				}
			}).setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					dialog.dismiss();
				}

			}).show();
		}
	}
}

